﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using RN.ERP.Web.BasicService;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.ZtbService;
using Newtonsoft.Json;
using System.Web.SessionState;
using Fly.Common.Linq;
using System.IO;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// LoginExpertHandler 的摘要说明
    /// </summary>
    public class LoginExpertHandler : IHttpHandler, IRequiresSessionState
    {
        private string AppID
        {
            get
            {
                return HttpContext.Current.Application[ApplicationConstant.APPLICATION_ID].ToString();
            }
        }

        private string SysArea
        {
            get
            {
                return ConfigurationManager.AppSettings["sysArea"];
            }
        }

        private bool IsAppRightOpen
        {
            get
            {
                return ConfigurationManager.AppSettings["IsAppRightOpen"] == "true";
            }
        }

        public HttpContext Context { set; get; }
        //public void IsEmp()
        //{
        //    string isEmp = string.Empty;
        //    if (string.IsNullOrEmpty(isEmp))
        //    {

        //    }
        //}

        public void ProcessRequest(HttpContext context)
        {
            

            string funcType = context.Request["functype"] ?? string.Empty;
            switch (funcType)
            {
                case "OldEmp": CheckEmpInfo(context); break;
                default: LoginExpert(context); break;
            }
            
           
        }


        public void LoginExpert(HttpContext context)
        {
            string idNum = context.Request["idNum"] ?? string.Empty;
            string passWord = context.Request["passWord"] ?? string.Empty;
            string dogId = context.Request["dogId"] ?? string.Empty;
            string type = context.Request["type"] ?? string.Empty;
            string msg = null;
            if (!string.IsNullOrEmpty(idNum) && !string.IsNullOrEmpty(passWord))
            {
                BasicServiceClient client = new BasicServiceClient();
                string userStr = client.DoExpertLogin(idNum, passWord, AppID, string.Empty);
                UserInfo userInfo = JsonConvert.DeserializeObject<UserInfo>(userStr);
                if (userInfo.Result)
                {
                    Guid guid = Guid.Empty;
                    Guid.TryParse(userInfo.UserGuid, out guid);
                    SessionUserInfo sui = new SessionUserInfo();
                    sui = CreateSessionInfo(userInfo);
                    sui.RoleType = type;
                    HttpContext.Current.Session[SessionConstant.SESSION_USERINFO] = sui;
                    msg = "success";
                    context.Response.Cookies[CookieConstant.COOKIE_USERGUID].Value = userInfo.UserGuid.ToString();
                }
                else
                {
                    msg = userInfo.Message;
                }
            }
            else
            {
                msg = "登录失败！";
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write(msg);
 
        }

        /// <summary>
        /// 验证老专家证号和手机号
        /// </summary>
        public void CheckEmpInfo(HttpContext context)
        {
            string Phone = context.Request["phone"] ?? string.Empty;
            string CerdentialsCode = context.Request["CerdentialsCode"] ?? string.Empty;

            if (!string.IsNullOrEmpty(Phone) && !string.IsNullOrEmpty(CerdentialsCode))
            {
                BasicServiceClient client = new BasicServiceClient();
                UserInfo userInfo = JsonConvert.DeserializeObject<UserInfo>(client.CheckEmpInfo(CerdentialsCode, Phone, string.Empty));
                if (userInfo.Result)
                {
                    ////生成session
                    HttpContext.Current.Session[SessionConstant.SESSION_EXPERT_MOBILE] = Phone;
                    ////想前台返回数据
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("success");
                }
                else
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("failed");
                }
            }
        }


        ////创建Session信息
        private SessionUserInfo CreateSessionInfo(UserInfo userInfo)
        {
            SessionUserInfo sui = new SessionUserInfo();
            sui.UserName = userInfo.UserName;
            sui.Name = userInfo.Name;
            sui.CorpUserGuid = userInfo.UserGuid;
            sui.DogId = userInfo.DogId;
            sui.RoleId = userInfo.RoleId;
            sui.FuncPerm = userInfo.FuncPerm;
            sui.AreaCode = userInfo.AreaCode;
            sui.LocalArea = userInfo.AreaCode2;
            sui.RoleTypeTitle = userInfo.RoleTypeTitle;
            sui.CurrentArea = string.IsNullOrEmpty(userInfo.AreaCode) ? string.Empty : userInfo.AreaCode.Substring(0, 2);
            string sysArea = ConfigurationManager.AppSettings["sysArea"];
            if (!string.IsNullOrEmpty(sysArea) && sysArea != sui.CurrentArea)
            {
                sui.CurrentArea = sysArea;
            }
            sui.UserTel = userInfo.UserTel;
            return sui;
        }

        private bool IsAppRightValid(string UserGuid)
        {
            BasicServiceClient client = new BasicServiceClient();
            return client.IsAppRightValid(int.Parse(AppID), Guid.Parse(UserGuid), SysArea);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        //private void TokenLogin(HttpContext context, UserInfo user, Tb_Corp_CompanyInfo corp)
        //{
        //    #region 令牌 edit by duan_yg
        //    //产生令牌
        //    string tokenValue = Guid.NewGuid().ToString().ToUpper();

        //    context.Response.Cookies.Add(new HttpCookie("LoginToken", tokenValue));
        //    HttpContext.Current.Session["token2"] = tokenValue;
        //    try
        //    {
        //        //WriteLog(string.Format("tokenValue:{0},Name:{1}", tokenValue, model.OldUser.Name));
        //        //产生主站凭证
        //        TokenService.TokenServiceSoapClient client = new TokenService.TokenServiceSoapClient();
        //        TokenService.DistriLogin userinfo = new TokenService.DistriLogin();
        //        userinfo.AreaCode = user.AreaCode;
        //        userinfo.RealAreaCode = "";
        //        userinfo.bGrade = string.IsNullOrEmpty(user.RoleId) ? -1 : int.Parse(user.RoleId);
        //        userinfo.ClassId = corp.classID;
        //        userinfo.CorpGuid = corp.CorpGuid;
        //        userinfo.isAdmin = user.RoleType != "User";
        //        userinfo.Name = user.Name;
        //        Guid userGuid = Guid.Empty;
        //        Guid.TryParse(user.UserGuid, out userGuid);
        //        userinfo.UserGuid = userGuid;
        //        userinfo.UserName = user.UserName;
        //        userinfo.DogId = string.IsNullOrEmpty(user.DogId) ? -1 : int.Parse(user.DogId);
        //        userinfo.UserID = user.UserID;
        //        userinfo.CorpID = corp.ID;
        //        client.TokenInsert(tokenValue, userinfo);
        //        //WriteLog(tokenValue + "写入缓存成功");
        //    }
        //    catch (Exception ex)
        //    {
        //        //WriteLog(string.Format("出错：tokenValue:{0},Name:{1}出错信息：{2}", tokenValue, model.OldUser.Name, ex.Message));
        //        //WriteLog(tokenValue+"写入缓存出错"+ex.Message);
        //    }

        //    #endregion
        //}

        /// <summary>
        /// 输出
        /// </summary>
        private void P(string str)
        {
            Context.Response.Write(str);
            Context.Response.Flush();
            Context.Response.End();
        }
    }
}
